import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import axios from 'axios'

export default new Vuex.Store({
    state: {
        list : [],   //存放所有数据
        dialogList : {},   //存详情弹窗数据
        cartList : [], //购物车数据
    },
    mutations: {
        // 更新数据列表
        getlist(state,payload){
            state.list = payload
        },
        // 详情弹窗数据
        getDialog(state,payload){
            state.list.forEach(val => {
                val.list.forEach(item => {
                    if(item.id === payload.id){
                        state.dialogList = item
                    }
                })
            })
        },
        //改变弹窗详情里商品数量
        changeDetail(state,count){
            state.dialogList.count = count;
        },
        //改变商品数量
        changeCount(state,{item,count}){
            state.cartList.forEach(val => {
                if(val.id === item.id){
                    console.log(val);
                    val.count = count;
                    if(val.count === 0){
                        state.cartList = state.cartList.filter(val =>val.id != item.id)
                    }
                }
            })
        },
        // 改变购物袋数量
        changeCart(state,payload){
            let cur = state.cartList.find(val => val.id === payload.id) 
            if(!cur){
                state.cartList.push(payload); 
            }else{
                cur.count ++
            }
        },
        //清空购物车
        clear(state){
            state.cartList.forEach(val => {
                val.count = 0
            })
            state.cartList = [];
        },
    },
    actions: {
        // 请求数据列表
        async setlist({ commit }){
            const res = await axios.post('/list')
            commit('getlist',res.data)
        }
    },
    getters : {
        //计算总数
        totalNum(state){
            return  state.cartList.reduce((prev,next) => {
                return prev + (next.checked ? next.count : 0)
            },0)
        },
        // 计算总价
        totalPrice(state){
            return  state.cartList.reduce((prev,next) => {
                return prev + (next.checked ? next.count * next.price : 0)
            },0)
        },
    },
    modules: {
    }
})
